const LOADING = '数据加载中';
const EMPTY = '选择条件内无数据';

/*生成随机数组*/
function randomFun(count, baseNum, diffNum, decimal) {//count数组长度, baseNum基础值, diffNum浮动值，decimal保留几位小数，
    var data = [];
    for (var i = 0; i < count; i++) {
        data[i] = (Math.random() * diffNum + baseNum).toFixed(decimal);
    }
    return data;
}

function increaseArr(count, begin) {//count长度,begin起始值
    var data = [];
    for (var i = 0; i < count; i++) {
        data[i] = '6-' + (i + begin);
    }
    return data;
}

function TimeNow() {
    var myDate = new Date();
    var year = myDate.getFullYear();
    var month = myDate.getMonth() + 1;
    var date = myDate.getDate();
    var hour = myDate.getHours();
    var minute = myDate.getMinutes();
    var second = myDate.getSeconds();

    var now = [year, month, date].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':');
    return now;
}

function TimeNowUnsign() {
    var myDate = new Date();
    var year = myDate.getFullYear();
    var month = myDate.getMonth() + 1;
    var date = myDate.getDate();
    var hour = myDate.getHours();
    var minute = myDate.getMinutes();
    var second = myDate.getSeconds();
    var now = [year, month, date].map(formatNumber).join('') + [hour, minute, second].map(formatNumber).join('');
    return now;
}

//日期时间处理
function formatNumber(s) {
    return s < 10 ? '0' + s : s;
}

/*截取地址栏参数*/
function getQueryString(name) {
    var result = decodeURI(window.location.search).match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
    if (result == null || result.length < 1) {
        return "";
    }
    return result[1];
}

function set_paging2(e, dm) {
    $("#page").paging({
        pageNo: 1,
        totalPage: Math.ceil(e / 5),
        totalSize: e,
        callback: function (num) {
            set_tr2(num, dm);
        }
    });
    set_tr2(1, dm);
    if (e < 1) {
        dm.empty();
        dm.append($("<tr><td align='center' colspan='15'>选择条件内无数据</td></tr>"));
    }
    ;
}

/* 设置分页，条件：分页组件id：page，表格id：data_table，每页展示10行 */
function set_paging(e) {
    $("#page").paging({
        pageNo: 1,
        totalPage: Math.ceil(e / 10),
        totalSize: e,
        callback: function (num) {
            set_tr(num);
        }
    });
    set_tr(1);
    if (e < 1) {
        $('table tbody').empty();
        $("table tbody").append($("<tr><td align='center' colspan='15'>选择条件内无数据</td></tr>"));
    }
    ;
}

// 设置显示的行
function set_tr2(e) {
    var start = (e - 1) * 5 + 1;
    var end = e * 5;
    $('#maintenance_List  tbody tr').addClass('d-none');
    for (var i = start; i <= end; i++) { // tr_len是要控制的tr个数
        $("#tr_" + i).removeClass('d-none');
    }
}

// 设置显示的行
function set_tr(e) {
    var start = (e - 1) * 10 + 1;
    var end = e * 10;
    $('table tbody tr').addClass('d-none');
    for (var i = start; i <= end; i++) { // tr_len是要控制的tr个数
        $("#tr_" + i).removeClass('d-none');
    }
}

/*加载企业信息下拉框*/
function loadEnterprise() {
    getJson("/enterprise/findEnterpriseS", null, 'GET', function (result) {
        if (result.code == 200) {
            let data = result.payload.data;
            $("#company-list").empty();
            $(new Option("选择企业", "")).appendTo($("#company-list"));
            for (let i = 0; i < data.length; i++) {
                $(new Option(data[i].name, data[i].id)).appendTo($("#company-list"));
                $(new Option(data[i].name, data[i].id)).appendTo($("#validationCustom06"));
            }
        } else {
            myAlert("提示", result.message);
        }
    })
}

/*加载企业信息下拉框*/
function loadCompanyList() {
    getJson("/enterprise/findEnterpriseS", null, 'GET', function (res) {
        if (res.code == 200) {
            var resData = res.payload.data;
            resData.map(function (item, index) {
                item.text = item.name;
            });
            $('#company-list').selectivity({
                items: resData,
                placeholder: '选择企业'
            });
        } else {
            myAlert("提示", res.message);
        }
    })

}

/* 点缩略图查看大图 */
//需配合模态弹窗viewImageModal服用
$('body').delegate('.img-preview', 'click', function () {
    $('#viewImageModal').modal();
    $('#img_preview_area').prop('src', $(this).prop('src'));
});

/* 点缩略图查看大图 */
//需配合模态弹窗viewImageModal服用
$('body').delegate('.img-preview', 'click', function () {
    showImpLoading('加载中');
    let url = $(this).prop('src');
    let url_origin = $(this).attr('data-origin');
    if (!isNull(url_origin)) {
        url = url_origin;
    }
    $('#img_preview_area').prop('src', url);
    $('#img_preview_area')[0].onload = function () {
        $('#viewImageModal').modal();
        hideLoading();
    }
    $('#img_preview_area')[0].onerror = function () {
        $('#img_preview_area').prop('src', '../customize/images/no-photo.png');
        $('#viewImageModal').modal();
        hideLoading();
    }
})

/*由原图路径拼接缩略图路径*/
function concatMinImgUrl(url) {
    if (!isNull(url)) {
        return url.replace('/', '/min');
    } else {
        return url;
    }
}

/**
 *获取当前时间
 *format=1精确到天
 *format=2精确到分
 */
function getCurrentDate(format) {
    var now = new Date();
    var year = now.getFullYear(); //得到年份
    var month = now.getMonth() + 1;//得到月份
    var date = now.getDate();//得到日期
    var day = now.getDay();//得到周几
    var hour = now.getHours();//得到小时
    var minu = now.getMinutes();//得到分钟
    var sec = now.getSeconds();//得到秒
    var time = "";
    //精确到天
    if (format == 1) {
        time = [year, month, date].map(formatNumber).join('-');
    }
    //精确到分
    else if (format == 2) {
        time = [year, month, date].map(formatNumber).join('-') + ' ' + [hour, minu, sec].map(formatNumber).join(':');
    }
    return time;
}

function sendMsg(e, phone, interval) {
    // let regular = /^((\+|00)86)?((134\d{4})|((13[0-3|5-9]|14[1|5-9]|15[0-9]|16[2|5|6|7]|17[0-8]|18[0-9]|19[0-2|5-9])\d{8}))$/;
    let regular = /^1[0-9]{10}$/;
    if (!regular.test(phone)) {
        showModalHint("none", "请输入正确的手机号");
        return;
    }
    $(e).css('pointerEvents', 'none');
    if (!phone) {
        $(e).css('pointerEvents', 'auto');
        return;
    }
    showModalHint('success', '验证码已发送，五分钟内有效');
    getJson('/sys/sendMsg', {
        username: phone
    }, 'GET', function () {
        let time = 60;
        if (interval) {
            clearInterval(interval);
        }
        interval = setInterval(function () {
            time--;
            $(e).text('重新发送 ' + time + 's');
            if (time <= 0) {
                clearInterval(interval);
                $(e).text('发送验证码');
                $(e).css('pointerEvents', 'auto');
            }
        }, 1000);
    })
}

function setPage(pageElement, index, totalPage, totalSize, callback) {
    $(pageElement).paging({
        pageNo: index,
        totalPage: totalPage,
        totalSize: totalSize,
        callback: function (num) {
            if (callback) {
                callback(num)
            }
        }
    });
}

function current() {
    var d = new Date(), str = '';
    str += d.getFullYear() + '-'; //获取当前年份
    str += d.getMonth() + 1 + '-'; //获取当前月份（0——11）
    str += d.getDate() + ' ';
    str += d.getHours() + ':';
    str += d.getMinutes() + ':';
    str += d.getSeconds();
    return str;
}

/*判断峰谷平*/
function judgeThePeakValleyFlat(time) {
    if (Number(time.substr(0, 2)) >= 0 && Number(time.substr(0, 2)) < 8) {//谷
        return 'min';
    } else if ((Number(time.substr(0, 2)) >= 12 && Number(time.substr(0, 2)) < 17) || (Number(time.substr(11, 2)) >= 21)) {
        return 'avg';
    } else {
        return 'max';
    }
}

/*由原图路径拼接缩略图路径*/
function concatMinImgUrl(url) {
    if (!isNull(url)) {
        return url.replace('/', '/min');
    } else {
        return url;
    }
}

/*判断开始时间和结束时间的差不超过30天*/
function oneMonthLimit(beginDate, endDate) {
    if (!beginDate && !endDate) {
        return;
    }
    let bDate = new Date(beginDate);
    let eDate = new Date(endDate);
    let difference = eDate.getTime() / (1000 * 60 * 60 * 24) - bDate.getTime() / (1000 * 60 * 60 * 24)
    return difference > 31;
}

/*判断开始时间和结束时间的差不超过7天*/
function oneWeekhLimit(beginDate, endDate) {
    if (!beginDate && !endDate) {
        return;
    }
    let bDate = new Date(beginDate);
    let eDate = new Date(endDate);
    let difference = eDate.getTime() / (1000 * 60 * 60 * 24) - bDate.getTime() / (1000 * 60 * 60 * 24)
    return difference > 7;
}

/*
        压缩图片，压缩后的图片为jpg格式
        file：获取到的图片文件
        max_width、max_height：压缩后的宽、高的最大值
        encoderOptions：图片质量，在指定图片格式为 image/jpeg 或 image/webp的情况下，可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围，将会使用默认值 0.92。
        callBack：压缩完成的回调函数，传参：压缩后的blob文件
    */
function compressPicture(file, max_width, max_height, encoderOptions, callBack) {
    var reader = new FileReader();
    if (!isNull(file)) {
        reader.readAsDataURL(file);
        reader.onload = function () {
            var img_base64 = reader.result;
            var img = new Image();
            img.src = img_base64;
            img.onload = function () {
                var image_width = max_width,
                    image_height = max_height;
                if (img.width < max_width && img.height < max_height) {//图片宽高均小于压缩值，使用原图尺寸
                    image_width = img.width;
                    image_height = img.height;
                } else {
                    //判断是横图还是竖图
                    if (img.width / img.height >= 1) {//横图或者正方形图
                        if (img.width >= max_width) {
                            image_width = max_width;
                            image_height = Math.round(img.height / (img.width / max_width));
                        }
                    } else {//竖图
                        if (img.height >= max_height) {
                            image_width = Math.round(img.width / (img.height / max_height));
                            image_height = max_height;
                        }
                    }
                }
                //新建canvas元素，用来对图片进行压缩
                var canvas = document.createElement("canvas");
                canvas.width = image_width;
                canvas.height = image_height;
                var context = canvas.getContext("2d");
                context.drawImage(img, 0, 0, image_width, image_height);
                var res_blob = canvas.toBlob(function (blob) {
                    if (callBack) {
                        callBack(blob);
                    }
                }, "image/jpeg", encoderOptions);//转化为Blob文件
            }
        }
    } else {
        callBack(null);
    }
}

function contrastTime(toDay, time) {
    var toDayTimestamp = new Date(toDay).valueOf();
    var timestamp = new Date(time).valueOf();
    return toDayTimestamp > timestamp
}

function loadDeviceType(select) {
    getJson("/deviceType/selectAllByParentId", null, 'GET', function (result) {
        buildSelectNoData($(select), result['payload']['data'], 'title', 'id', '选择设备类型');
    })
}
function buildTree(tree, funPath) {
    if (funPath == '/deviceType/selectDeviceTypeTree') {
        return tree;
    }
    //第一步,把有用的数据都提取出来
    let treeDataObj = {};
    for (let item of tree) {
        let typeArr = [
            {id: item.typeOne, title: item.typeOneName},
            {id: item.typeTow, title: item.typeTowName},
            {id: item.typeThree, title: item.typeThreeName},
        ];
        let id = item.typeThree || item.typeTow || item.typeOne;
        let ind = typeArr.findIndex((item) => {
            return item.id == id;
        });
        let pId = undefined;
        if (ind - 1 >= 0) {
            pId = typeArr[ind - 1].id;
        }
        treeDataObj[id] = {
            id: id,
            title: typeArr[ind].title,
            children: [],
            typeArr: typeArr,
            spread: true,
            ind: ind,
            pId: pId
        }
    }
//第二步,建立层级关系
    for (let key in treeDataObj) {
        let item = treeDataObj[key];
        if (item.pId) {
            if (treeDataObj[item.pId]) {
                treeDataObj[item.pId].children.push(item);
            } else {
                let pId = undefined;//上上
                let typeArr = item.typeArr;
                let ind = item.ind;
                if (ind - 2 >= 0) {
                    pId = typeArr[ind - 2].id;
                }
                let temp = {
                    id: item.pId,
                    title: typeArr[ind - 1].title,
                    pId: pId,
                    typeArr: typeArr,
                    spread: true,
                    children: []
                };//上
                temp.children.push(item);
                treeDataObj[item.pId] = temp;
            }

        }
    }
//第三步,去除无用数据
    for (let key in treeDataObj) {
        let item = treeDataObj[key];
        if (item.pId) {
            delete treeDataObj[key];
        }
    }

//第四部,还原成数组
    let treeData = [];
    for (let key in treeDataObj) {
        let item = treeDataObj[key];
        treeData.push(item);
    }
    return treeData;
}
